//
//  BaseViewController.m
//  XHNShangChengMoBan
//
//  Created by 张铁军 on 16/8/13.
//  Copyright © 2016年 ping. All rights reserved.
//

#import "BaseViewController.h"
#import "FilesHeader.h"
#import "IQKeyboardManager.h"

@interface BaseViewController (){
    SVProgressHUD *SVHud;
}

@end

@implementation BaseViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self ksc];
    self.view.backgroundColor = [UIColor whiteColor];
    [self.navigationController.navigationBar setHidden:YES];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
}

-(void)ksc{
    if (KScreenHeight == 667 ) {
        _kscH = 1;
        _kscW = 1;
    }
    else
    {
        _kscH = KScreenHeight / 667;
        _kscW = KScreenWidth / 375;
    }
}
- (NSString*)dictionaryToJson:(NSDictionary *)dic
{
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    NSString * a =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    a = [a stringByReplacingOccurrencesOfString: @" " withString: @""];
    a = [a stringByReplacingOccurrencesOfString: @"\n" withString: @""];
    return a;
}

-(CGSize)jiSuanGaoDu:(NSString *)string{
    //内容
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]initWithString:string];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
    [paragraphStyle setLineSpacing:5];
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, string.length)];
    //获取计算高度
    CGSize contentSize = [string boundingRectWithSize:CGSizeMake(KScreenWidth-20, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:13]} context:nil].size;
    return contentSize;
}
#pragma mark- 又返回按钮的导航头部
/**
 导航头部 灰色背景 244 
 
 @param title Nsstring
 */
-(void)setNavTitleText:(NSString *)title{
    
    UIView *HeaderView = [[UIView alloc]init];
    HeaderView.backgroundColor = rgb(244, 244, 244);
    HeaderView.frame = CGRectMake(0, 0, KScreenWidth, Height_NavBar);

    UIButton *blackBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [blackBtn setImage:[UIImage imageNamed:@"pay_icon_3"] forState:0];
    [blackBtn addTarget:self action:@selector(black) forControlEvents:UIControlEventTouchUpInside];
    blackBtn.frame = CGRectMake(0, Height_StatusBar, 54, 44);
    [HeaderView addSubview:blackBtn];
    float WIDTH = KScreenWidth - blackBtn.right - 54 - 10;
    //lable
    UILabel *lable=[[UILabel alloc]initWithFrame:CGRectMake(blackBtn.right + 10, Height_StatusBar, WIDTH, 44)];
    lable.textAlignment = NSTextAlignmentCenter;
//    lable.textColor = [UIColor whiteColor];
    lable.textColor = rgb_51;
    [HeaderView addSubview:lable];
    lable.centerXv = HeaderView.centerXv;
    lable.text=title;
    lable.font=[UIFont boldSystemFontOfSize:18];
    [self.view addSubview:HeaderView];
}

/**
 导航头部 白色背景

 @param title Nsstring
 */
-(void)setNavBackgroundWhiteColorTitleText:(NSString *)title{
    UIView *HeaderView = [[UIView alloc]init];
    HeaderView.frame = CGRectMake(0, 0, KScreenWidth, Height_NavBar);
    HeaderView.backgroundColor = [UIColor whiteColor];
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setImage:[UIImage imageNamed:@"back"] forState:0];
    [backBtn addTarget:self action:@selector(black) forControlEvents:UIControlEventTouchUpInside];
    backBtn.frame = CGRectMake(0, Height_StatusBar, 52, 44);
    [HeaderView addSubview:backBtn];
    float WIDTH = KScreenWidth - backBtn.right - 54 - 10;
    //lable
    UILabel *lable=[[UILabel alloc]initWithFrame:CGRectMake(backBtn.right + 10, Height_StatusBar, WIDTH, 44)];
    lable.textAlignment = NSTextAlignmentCenter;
    [HeaderView addSubview:lable];
    lable.centerXv = HeaderView.centerXv;
    lable.text=title;
    self.titleL = lable;
    lable.font=[UIFont boldSystemFontOfSize:18];
    [self.view addSubview:HeaderView];
}

-(void)setNavBackgroundImageTitleText:(NSString *)title{
    UIView *HeaderView = [[UIView alloc]init];
    HeaderView.frame = CGRectMake(0, 0, KScreenWidth, Height_NavBar);
    HeaderView.backgroundColor = [UIColor whiteColor];
    
//    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, Height_NavBar)];
//    imageView.image = [UIImage imageNamed:@"register_img_1"];
//    [HeaderView addSubview:imageView];
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setImage:[UIImage imageNamed:@"register_icon_7"] forState:0];
    [backBtn addTarget:self action:@selector(black) forControlEvents:UIControlEventTouchUpInside];
    backBtn.frame = CGRectMake(0, Height_StatusBar, 52, 44);
    [HeaderView addSubview:backBtn];
    float WIDTH = KScreenWidth - backBtn.right - 54 - 10;
    //lable
    UILabel *lable=[[UILabel alloc]initWithFrame:CGRectMake(backBtn.right + 10, Height_StatusBar, WIDTH, 44)];
    lable.textAlignment = NSTextAlignmentCenter;
    [HeaderView addSubview:lable];
    lable.centerXv = HeaderView.centerXv;
    lable.text=title;
    lable.textColor = [UIColor blackColor];
    self.titleL = lable;
    lable.font=[UIFont boldSystemFontOfSize:18];
    [self.view addSubview:HeaderView];
}

-(void)setNavgationTitle:(NSString *)string{
    UIView *HeaderView = [[UIView alloc]init];
    HeaderView.frame = CGRectMake(0, 0, KScreenWidth, Height_NavBar);
    HeaderView.backgroundColor = [UIColor whiteColor];
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, Height_NavBar)];
    imageView.image = [UIImage imageNamed:@"register_img_1"];
    [HeaderView addSubview:imageView];
    
    UILabel *lable=[[UILabel alloc]initWithFrame:CGRectMake(0, Height_StatusBar, KScreenWidth, 44)];
    lable.textAlignment = NSTextAlignmentCenter;
    lable.textColor = [UIColor whiteColor];
    [HeaderView addSubview:lable];
    lable.centerXv = HeaderView.centerXv;
    lable.text=string;
//    self.titleL = lable;
    lable.font=[UIFont boldSystemFontOfSize:18];
    [self.view addSubview:HeaderView];
    
    
}

-(void)black{
    [self.navigationController popViewControllerAnimated:YES];
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark- 将数据保存到缓存中
-(void)setCacheFileName:(NSString *)string andSaveType:(NSArray *)array{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    //    NSLog(@"home = %@",paths[0]);
    NSString *cachePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:string];
//    NSLog(@"cachePath = %@",cachePath);
    [array writeToFile:cachePath atomically:YES];
}
#pragma mark- 获取缓存路径
-(NSString *)getCacheFilePath:(NSString *)string{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cachePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:string];
    return cachePath;
}

#pragma mark - HUD
- (void)showWithTitle:(NSString *)title
{
    [SVProgressHUD showSuccessWithStatus:title];
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleCustom];
    [SVProgressHUD setBackgroundColor:rgb(245, 245, 245)];
    [SVProgressHUD setImageViewSize:CGSizeMake(0, 0)];
    [SVProgressHUD dismissWithDelay:1.f];
}
#pragma mark- 菊花
- (void)showHUDWithString:(NSString *)string {
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
    [SVProgressHUD setDefaultAnimationType:SVProgressHUDAnimationTypeNative];
    [SVProgressHUD showWithStatus:string];
    
   
}
- (void)hideHUD {
    [SVProgressHUD dismiss];
}
-(void)callServicePhone:(NSString *)str{
    UIAlertController *alert=[UIAlertController alertControllerWithTitle:@"联系客服" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *tureAction=[UIAlertAction actionWithTitle:str style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

        NSMutableString * string=[[NSMutableString alloc] initWithFormat:@"tel:%@",str];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:string]];
    }];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        [self.navigationController popViewControllerAnimated:YES];
    }];
    [alert addAction:tureAction];
    [alert addAction:cancelAction];
    [self presentViewController:alert animated:YES completion:nil];
}
-(UIImageView *)addNoneSearch{
    UIImageView *imageErr = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 320*_kscW, 320*_kscW)];
    imageErr.hidden = YES;
    imageErr.centerXv = KScreenWidth/2;
    imageErr.contentMode = UIViewContentModeScaleAspectFill;
    imageErr.image = [UIImage imageNamed:@"img_none_search"];
    return imageErr;
}
-(UIImageView *)addNoneGoodslist{
    UIImageView *imageErr = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 320*_kscW, 320*_kscW)];
    imageErr.hidden = YES;
    imageErr.centerXv = KScreenWidth/2;
    imageErr.contentMode = UIViewContentModeScaleAspectFill;
    imageErr.image = [UIImage imageNamed:@"img_none_order"];
    return imageErr;
}

-(UIImageView *)addNoneShoppingCart{
    UIImageView *imageErr = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 320*_kscW, 320*_kscW)];
    imageErr.hidden = YES;
    imageErr.centerXv = KScreenWidth/2;
    imageErr.contentMode = UIViewContentModeScaleAspectFill;
    imageErr.image = [UIImage imageNamed:@"img_none_shoppingcart"];
    return imageErr;
}
-(NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}
//设置键盘
-(void)setKeyboard{
    [[IQKeyboardManager sharedManager] setEnable:YES];
//    [[IQKeyboardManager sharedManager] setEnableAutoToolbar:YES];
    [[IQKeyboardManager sharedManager] setShouldResignOnTouchOutside:YES];
}
//取消键盘设置
-(void)cancalKeyboard{
    [[IQKeyboardManager sharedManager] setEnable:NO];
//    [[IQKeyboardManager sharedManager] setEnableAutoToolbar:NO];
    [[IQKeyboardManager sharedManager] setShouldResignOnTouchOutside:NO];
}
//返回按钮
-(void)drawBackButton{
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setImage:[UIImage imageNamed:@"login_icon_3"] forState:0];
    [backBtn addTarget:self action:@selector(clickBack) forControlEvents:UIControlEventTouchUpInside];
    backBtn.frame = CGRectMake(0, Height_StatusBar, 52, 44);
    [self.view addSubview:backBtn];
}

-(void)clickBack{
    [self.navigationController popViewControllerAnimated:YES];
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (float)widthForString:(NSString *)value fontSize:(float)fontSize//根据字符串的的长度来计算UITextView的高度
{
    CGSize size = [value boundingRectWithSize:CGSizeMake(MAXFLOAT, 20) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:fontSize]} context:nil].size;
    return size.width;
    
}
- (float)heightForString:(NSString *)value fontSize:(float)fontSize andWidth:(float)width//根据字符串的的长度来计算UITextView的高度
{
    CGSize size = [value boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:fontSize]} context:nil].size;
    return size.height;
    
}


-(void)setRightBtnWithName:(NSString *)title{
    UIButton *rightBtn = [[UIButton alloc]init];
    [rightBtn setTitle:title forState:UIControlStateNormal];
    [self.view addSubview:rightBtn];
    [rightBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [rightBtn.titleLabel setFont:[UIFont systemFontOfSize:16]];
    [rightBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@44);
        make.right.equalTo(self.view.mas_right).offset(-10);
        make.top.equalTo(self.view.mas_top).offset(Height_StatusBar);
    }];
    [rightBtn sizeToFit];
    self.rightBtn = rightBtn;
}
- (void)startTime:(UIButton *)VerificationCodeButton
{
    // 剩余的时间（必须用__block修饰，以便在block中使用）
    __block NSInteger remainTime = 59;
    // 获取全局队列
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    // 每隔1s钟执行一次
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    // 在queue中执行event_handler事件
    dispatch_source_set_event_handler(timer, ^{
        if (remainTime <= 0) { // 倒计时结束
            dispatch_source_cancel(timer);
            // 回到主线程
            dispatch_async(dispatch_get_main_queue(), ^{
                
                VerificationCodeButton.userInteractionEnabled = YES;
                [VerificationCodeButton setTitle:@"重新发送" forState:0];
            });
        } else {
            NSString *timeStr = [NSString stringWithFormat:@"%ld", remainTime];
            // 回到主线程更新UI
            dispatch_async(dispatch_get_main_queue(), ^{
                [VerificationCodeButton setTitle:[NSString stringWithFormat:@"%@ S",timeStr] forState:0];
                VerificationCodeButton.userInteractionEnabled = NO;
            });
            remainTime--;
        }
    });
    dispatch_resume(timer);
}

-(NSString *)doubleToString:(double)doubleNum{
    NSString *dStr      = [NSString stringWithFormat:@"%f", doubleNum];
    NSDecimalNumber *dn = [NSDecimalNumber decimalNumberWithString:dStr];
    return [dn stringValue];
}
#pragma mark- 四舍五入
-(NSString*)notRounding:(double)price afterPoint:(NSInteger)position
{
    NSDecimalNumberHandler* roundingHandler = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundPlain scale:position raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:NO];
    
    NSDecimalNumber* returnNumber;
    
    NSDecimalNumber* ouncesDecimal = [[NSDecimalNumber alloc]initWithDouble:price];
    
    returnNumber = [ouncesDecimal decimalNumberByRoundingAccordingToBehavior:roundingHandler];
    
    return [NSString stringWithFormat:@"%@",returnNumber];
}



-(void)attributedStringSourceString:(NSString *)string andFont:(UIFont *)font andPlanceString:(NSString *)planceStr andSourceLabel:(UILabel *)lable{
    
    NSMutableAttributedString *AttributedStr = [[NSMutableAttributedString alloc]initWithString:string];
    NSRange range = [string rangeOfString:planceStr];
    [AttributedStr addAttribute:NSFontAttributeName value:font range:range];
    lable.attributedText = AttributedStr;
}




@end
